package com.roc.web.action.excel;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.pojo.OrgBean;
import com.roc.pojo.SettingBean;
import com.roc.service.IExcelService;
import com.roc.service.IMerchantServices;
import com.roc.service.IPagenitionService;
import com.roc.service.IorgService;
import com.roc.util.Constance;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;
import com.roc.web.action.setting.SettingTotalSearchCondition;

@Component
@Scope("prototype")
@Namespace("/settingTotalListExcel")
@SuppressWarnings("all")
public class settingTotalListExcel extends PaginationBaseAction{
	static Logger  logger=Logger.getLogger(EstransExcel.class);
	private Operators operators;
	private List<Object> profitRsList = new ArrayList<Object>();
	private SettingTotalSearchCondition searchCondition;
	private List<OrgBean> orgList=new ArrayList<OrgBean>();
	private InputStream excelFile;
	private String  excelName;
	@Autowired
	IorgService orgService;
	@Autowired
	IMerchantServices merchantServices;
	@Autowired
	IPagenitionService pagenitionService;
	@Autowired
	IExcelService excelService;
	

	
	@Action(value="settingTotalExcel",results = {@Result(name="success",type="stream"
			,params = { "contentType", "application/vnd.ms-excel", "inputName",  
			            "excelFile","contentDisposition",  "attachment;filename=${excelName}.xls",
 "bufferSize", "1024*3" }),@Result(name="error",location="/pages/setting/settingtotallist.jsp") }) 
	public String settingTotalExcel(){
		Operators logingOperators = (Operators) getSession().getAttribute(
				Constant.SESSION_LOGIN_MERCHANT);
		if(!(logingOperators.getRoleType().equals("00")||logingOperators.getRoleType().equals("01")||logingOperators.getRoleType().equals("02"))){
			return ERROR;
		}
		
		try{
			orgList=orgService.listOrgs(logingOperators);
			// 系统管理员查看全部，代理只能看到本机构下的。
			//searchCondition.setRoleType(logingMerchant.getRoleType());
			if(Constance.OPERATORS_FLAG_OEM.equals(logingOperators.getFlag())){
				if(Role.MERCHANT.getCode().equals(logingOperators.getRoleType())){
					searchCondition.setMerNo(logingOperators.getAccountNo());
				}else if(Role.AGENT.getCode().equals(logingOperators.getRoleType())){
					if(searchCondition.getAgentId()<=0){
						//查询出所有的下级代理ID
						List<Operators> list = merchantServices.listAllSubMerchants(logingOperators.getId());
						if(list!=null&&list.size()>0){
							long[] st =listtoarry(list);
							searchCondition.setAgentIds(st);
						}else{
							long[] st={logingOperators.getId()};
							searchCondition.setAgentIds(st);
						}
						
					}
				}else{
					searchCondition.setOrgCode(logingOperators.getOrgCode());
				}
			}
			
			
			int rows = pagenitionService.countSQL(searchCondition);
			List<SettingBean> settingList = new ArrayList<SettingBean>();
			if (rows > 0) {
				searchRsList = pagenitionService.findAllSQL(searchCondition,
						calcuStart(getCurrentPage()), rows);
				if (searchRsList != null && searchRsList.size() > 0) {
					Iterator iterator = searchRsList.iterator();
					while (iterator.hasNext()) {
						Object[] obj = (Object[]) iterator.next();
						SettingBean sett = new SettingBean();
						if (obj[0] != null && !"".equals(obj[0])) {
							sett.setOrderno(obj[0].toString());
						}
						if (obj[1] != null && !"".equals(obj[1])) {
							sett.setMerchantno(obj[1].toString());
						}
						if (obj[2] != null && !"".equals(obj[2])) {
							sett.setMerchantname(obj[2].toString());
						}
						if (obj[3] != null && !"".equals(obj[3])) {
							sett.setSettledate(obj[3].toString());
						}
						if (obj[4] != null && !"".equals(obj[4])) {
							sett.setFreezeflag(obj[4].toString());
						}
						if (obj[5] != null && !"".equals(obj[5])) {
							sett.setTotalamt(Double.valueOf(obj[5].toString()));
						}
						if (obj[6] != null && !"".equals(obj[6])) {
							sett
									.setTotalnum(Integer.valueOf(obj[6]
											.toString()));
						}
						if (obj[7] != null && !"".equals(obj[7])) {
							sett.setMerchantfee(Double.valueOf(obj[7]
									.toString()));
						}
						if (obj[8] != null && !"".equals(obj[8])) {
							sett.setMerchantsettleamt(Double.valueOf(obj[8]
									.toString()));
						}
						if (obj[9] != null && !"".equals(obj[9])) {
							sett.setSettleflag(obj[9].toString());
						}
						if (obj[10] != null && !"".equals(obj[10])) {
							sett.setBatchno(obj[10].toString());
						}

						settingList.add(sett);
					}
				}
			}
			
			HSSFWorkbook work=excelService.settingTotalListTransQueryExcel(settingList,searchCondition.getMinDate(),searchCondition.getMaxDate());
			 ByteArrayOutputStream output = new ByteArrayOutputStream();  
			         work.write(output);  
			   
			        byte[] ba = output.toByteArray();  
			         excelFile = new ByteArrayInputStream(ba);  
			         output.flush();  
			         output.close();  
			
		}catch(Exception e){
			logger.info("######结算导出Excel失败######");
			addActionError(e.getMessage());
			return ERROR;
		}
		return SUCCESS;
	}
	
	
	public long[] listtoarry(List<Operators> list){
		long[] st=new long[list.size()] ;
		for(int i=0;i<list.size();i++){
			st[i]=list.get(i).getId();
		}
		return st;
	}
	
	
	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		// TODO Auto-generated method stub
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		// TODO Auto-generated method stub
		this.setSearchConditionToSubClass(searchCondition);
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		// TODO Auto-generated method stub
		getSession().setAttribute(SEARCH_SESSION_BEAN_TOTALSETTING, searchCondition);
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		// TODO Auto-generated method stub
		return (SettingTotalSearchCondition) getSession().getAttribute(
				SEARCH_SESSION_BEAN_TOTALSETTING);
	}

	@Override
	protected String getInitPageSize() {
		// TODO Auto-generated method stub
		return null;
	}


	public Operators getOperators() {
		return operators;
	}


	public void setOperators(Operators operators) {
		this.operators = operators;
	}


	public List<Object> getProfitRsList() {
		return profitRsList;
	}


	public void setProfitRsList(List<Object> profitRsList) {
		this.profitRsList = profitRsList;
	}


	public SettingTotalSearchCondition getSearchCondition() {
		return searchCondition;
	}


	public void setSearchCondition(SettingTotalSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}


	public List<OrgBean> getOrgList() {
		return orgList;
	}


	public void setOrgList(List<OrgBean> orgList) {
		this.orgList = orgList;
	}


	public InputStream getExcelFile() {
		return excelFile;
	}


	public void setExcelFile(InputStream excelFile) {
		this.excelFile = excelFile;
	}


	public String getExcelName() {
		String excelName="结算明细"+Constance.formateDate();
		 
			try {
				excelName = new String(excelName.getBytes(),"ISO8859-1");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				logger.info("生成excel名称失败了！");
			}
		 
		return  excelName;
		
	}


	public void setExcelName(String excelName) {
		this.excelName = excelName;
	}
	
	
}
